package com.myclasses;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class Contacts {

	private static Contacts contacts;
	private Contacts() {
		serwis = null;
		user = null;
		contactsMap = new HashMap<Integer, ContactEntry>();
		System.err.println("tworze kontakt");
		if (serwis == null) {
			serwis = this.authenticate("iosr.team11@gmail.com", "iosr_team");
			System.out.println("podlaczanie");
		}
		// groupsMap = new HashMap<Integer, ContactGroupEntry>();
	}
	public static Contacts getInstance(){
		if (contacts==null)
			contacts= new Contacts();
		return contacts;
	}

	public ContactsService serwis;
	public String user;
	private Map<Integer, ContactEntry> contactsMap;

	// private Map<Integer, ContactGroupEntry> groupsMap;

	public Map<Integer, ContactEntry> getContactsMap() {
		return contactsMap;
	}

	public void setContactsMap(Map<Integer, ContactEntry> contactsMap) {
		this.contactsMap = contactsMap;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getUser() {
		return this.user;
	}

	public void setSerwis(ContactsService serwis) {
		this.serwis = serwis;
	}

	public ContactsService getSerwis() {
		return this.serwis;
	}

	public List<UserItemBean> getContactsFromServer() {
		try {
			URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/"
					+ user + "/full");
			ContactFeed resultFeed = serwis.getFeed(feedUrl, ContactFeed.class);
			List<UserItemBean> lista = new ArrayList<UserItemBean>();
			lista.clear();
			for (ContactEntry entry : resultFeed.getEntries()) {
				String name = entry.getTitle().getPlainText();
				StringBuffer mail = new StringBuffer();
				String indexNo = null;
				StringBuffer group = new StringBuffer();
				boolean nextgrp = false;
				for (Email email : entry.getEmailAddresses()) {
					mail
							.append(" "
									+ (email.getAddress() + " <- " + email
											.getRel()
											.substring(
													email.getRel().indexOf("#") + 1)));
					mail.append("\n");// Zwraca kolejne e-maile dla danej osoby
				}
				if (entry.getExtendedProperties() != null)
				for (ExtendedProperty prop : entry.getExtendedProperties()) {
					if (prop != null) {
						if (prop.getName().equals("indexNo")){
							indexNo=prop.getValue();
							break;
						}
					}
					// else if (prop.getExtensionLocalName().equals("")))
				}
				if (entry.getGroupMembershipInfos() != null) {
					for (GroupMembershipInfo infoGrp : entry
							.getGroupMembershipInfos()) {
						ContactGroupEntry entryGrp= serwis.getEntry(new URL(infoGrp.getHref()), ContactGroupEntry.class);
						if (entryGrp!=null){
							group.append(entryGrp.getTitle().getPlainText());
						}
					}
				}
				UserItemBean bean = new UserItemBean(name, group.toString(),
						mail.toString(), indexNo);
				lista.add(bean);
			}
			return lista;
		} catch (Exception e) {
			System.out.println("ERR --- List");
			e.printStackTrace();
			return null;
		}
	}

	public boolean insertContact(String name, String email, String indexNo,
			String group) {
		System.out.println("Dodaje KONTAKT ==========================");
		System.out.println("Name: " + name);
		System.out.println("Index: " + indexNo);
		System.out.println("Group: " + group);
		System.out.println("Email: " + email);
		System.out.println("=========================================");
		ContactEntry entry = new ContactEntry();
		entry.setTitle(new PlainTextConstruct(name));
		Email emailAddress = new Email();
		emailAddress.setAddress(email);
		emailAddress.setPrimary(true);
		emailAddress.setRel("http://schemas.google.com/g/2005#home"); // <-ustawienie typu
		entry.addEmailAddress(emailAddress);
		// wyszukanie czy podana grupa istnieje jesli nie to tworzy grupe
		try {
			URL feedURL = new URL("http://www.google.com/m8/feeds/groups/"+user+"/full");
			ContactGroupFeed result = serwis.getFeed(feedURL, ContactGroupFeed.class);
			boolean groupNotExist=true;
			for (int i=0; i<result.getEntries().size(); i++){
				if (result.getEntries().get(i).getTitle().getPlainText().equals(group)){
					GroupMembershipInfo groupMembershipInfo = new GroupMembershipInfo();
					groupMembershipInfo.setHref(result.getEntries().get(i).getId());
					entry.addGroupMembershipInfo(groupMembershipInfo);
					groupNotExist=false;
				}
			}/*
			if (groupNotExist){
				ContactGroupEntry grpEntry = new ContactGroupEntry();
				grpEntry.setTitle(new PlainTextConstruct(group));
				URL postGrpURL = new URL("http://www.google.com/m8/feeds/groups/"+user+"/full");
				serwis.insert(postGrpURL, grpEntry);
				
				if (grpEntry!=null){
					GroupMembershipInfo groupMembershipInfo = new GroupMembershipInfo();
					groupMembershipInfo.setHref(grpEntry.getId());
					entry.addGroupMembershipInfo(groupMembershipInfo);
				}
			}*/
		}
		catch (Exception e){}
		
		
		// dodanie numeru indeksu
		ExtendedProperty extend = new ExtendedProperty();
		extend.setName("indexNo"); extend.setValue(indexNo);
		entry.getExtendedProperties().add(extend);
		
		try {
			/* cos na rodzaj polaczena z baza danych */
			URL postURL = new URL("http://www.google.com/m8/feeds/contacts/"
					+ user + "/full");
			serwis.insert(postURL, entry);
		} catch (ServiceException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/*
	 * public String getContacts(String email, String password){ String result =
	 * null; ContactsService serwis = authenticate(email, password); if (serwis
	 * == null){ return "<h1>Blad - zly login lub haslo</h1>"; } try{ result =
	 * printAllContacts(serwis,email); } catch (IOException e){ return
	 * "Blad - IOException"; } catch (ServiceException e){ return
	 * "Blad - ServiceException"; } return result; }
	 */

	// W ContactService przechowywane sa dane połączenia na ich podstawie
	// realizowane sa pozostałe wywołania
	public ContactsService authenticate(String user, String password) {
		serwis = new ContactsService("example");
		this.user = user;
		try {
			serwis.setUserCredentials(user, password);
		} catch (AuthenticationException e) {
			System.err.println("AUTH -- >> \\|/");
			return null;
		}
		return serwis;
	}

}
